package com.js.foodordersystem.controller;

import com.alibaba.fastjson.JSONObject;
import com.js.foodordersystem.entity.DishCategory;
import com.js.foodordersystem.service.DishCategoryService;
import com.js.foodordersystem.util.Result;

import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 菜品分类表(DishCategory)表控制层
 *
 * @author makejava
 * @since 2025-01-14 10:57:16
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("dishCategory")
public class DishCategoryController {
    /**
     * 服务对象
     */
    @Resource
    private DishCategoryService dishCategoryService;

    /**
     * 分页查询
     *
     * @param dishCategory 筛选条件
     * @param limit        分页对象
     * @param page         分页对象
     * @return 查询结果
     */
    @GetMapping("findAll")
    public Result findAll(DishCategory dishCategory, Integer limit, Integer page) {
        if (limit == null || page == null) {
            return Result.failure("limit和page不能为空");
        }
        return dishCategoryService.selectAll(dishCategory, limit, page);
    }

    /**
     * 查询全部分类
     * @author 史超杰
     * @date 2025/1/14 13:44
     */
    @GetMapping("findAllCategory")
    public Result findAllCategory() {
        return Result.success(this.dishCategoryService.list());
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("getById")
    public Result getById(Long id) {
        return Result.success(this.dishCategoryService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param dishCategory 实体
     * @return 新增结果
     */
    @PostMapping("add")
    public Result add(@RequestBody DishCategory dishCategory) {
        //判断是否为空
        if (dishCategory == null) {
            return Result.failure("参数不能为空");
        }

        if (this.dishCategoryService.save(dishCategory)) {
            return Result.success("添加成功");
        }
        return Result.failure("添加失败");
    }

    /**
     * 编辑数据
     *
     * @param dishCategory 实体
     * @return 编辑结果
     */
    @PostMapping("edit")
    public Result edit(@RequestBody DishCategory dishCategory) {
        //判断是否为空
        if (dishCategory == null) {
            return Result.failure("参数不能为空");
        }

        if (this.dishCategoryService.updateById(dishCategory)) {
            return Result.success("修改成功");
        }
        return Result.failure("修改失败");
    }

    /**
     * 删除数据
     *
     * @return 删除是否成功
     */
    @PostMapping("delete")
    public Result deleteById(@RequestBody JSONObject data) {
        Long id = data.getLong("dishCategoryId");
        //判断id是否为空
        if (id == null) {
            return Result.failure("id不能为空");
        }

        if (this.dishCategoryService.removeById(id)) {
            return Result.success("删除成功");
        }
        return Result.failure("删除失败");
    }

}

